import { _decorator , CameraComponent, Component, EventTouch, geometry, input, Input, physics, PhysicsSystem } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 3D物体触摸检测
 */
@ccclass('TouchEvent3D')
export class TouchEvent3D extends Component {

    @property({
        type: CameraComponent,
        tooltip: "渲染 3D 物体的 Camera"
    })
    mainCameraCom: CameraComponent = null

    private _ray = new geometry.Ray()

    /**
     * 击中时
     */
    public onHit: (collider_: physics.Collider) => void = null

    /**
     * 未击中时
     */
    public onNoHit: () => void = null

    /**
     * 添加触摸事件
     */
    public addEvent() {
        input.on(Input.EventType.TOUCH_START, this.touchStart, this)
    }

    /**
     * 注销触摸事件
     */
    public offEvent() {
        input.off(Input.EventType.TOUCH_START, this.touchStart, this)
    }

    /**
     * 
     * @param et 
     */
    private touchStart(et: EventTouch) {
        const touch = et.touch;
        this.mainCameraCom.screenPointToRay(touch.getLocationX(), touch.getLocationY(), this._ray);
        if (PhysicsSystem.instance.raycastClosest(this._ray)) {
            if (this.onHit) {
                this.onHit(PhysicsSystem.instance.raycastClosestResult.collider)
            }
        } else {
            if (this.onNoHit) {
                this.onNoHit()
            }
        }
    }
}


